<template>
  <div class="inspiration-editor">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <n-spin size="large" />
      <p class="loading-text">正在加载灵感内容...</p>
    </div>
    
    <!-- 空状态 -->
    <div v-else-if="isEmpty && isNew" class="empty-container">
      <n-empty description="暂无灵感内容">
        <template #extra>
          <n-button type="primary" @click="handleAddInspiration">创建灵感</n-button>
        </template>
      </n-empty>
    </div>
    
    <!-- 编辑器内容 -->
    <div v-else class="editor-container">
      <div class="editor-content">
        <!-- 根据当前活动标签页显示对应内容 -->
        <div v-if="activeTab === 'content'" class="editor-pane">
          <div v-if="!isPreviewMode" class="editor-input-container">
            <n-input
              v-model:value="inspirationContent"
              type="textarea"
              placeholder="请输入灵感内容，支持Markdown格式..."
              class="content-editor custom-scrollbar"
              ref="contentEditorRef"
              :disabled="contentLoading"
            />
            <!-- 内容加载遮罩动画 -->
            <div v-if="contentLoading" class="loading-overlay-container">
              <LoadingDots :visible="true" message="正在生成灵感内容" />
            </div>
          </div>
          <div v-else class="preview-pane custom-scrollbar" ref="contentPreviewRef">
            <MarkdownRenderer :content="inspirationContent" />
            <!-- 内容加载遮罩动画 -->
            <div v-if="contentLoading" class="loading-overlay-container">
              <LoadingDots :visible="true" message="正在生成灵感内容" />
            </div>
          </div>
        </div>
        
        <div v-if="activeTab === 'settings'" class="editor-pane">
          <div class="settings-form">
            <n-form :model="inspirationSettings" label-placement="left" label-width="100px">
              <n-form-item label="标题">
                <n-input 
                  v-model:value="inspirationSettings.title" 
                  placeholder="请输入灵感标题"
                />
              </n-form-item>
              
              <n-form-item label="标签">
                <n-dynamic-tags 
                  v-model:value="inspirationSettings.tags" 
                  placeholder="输入标签后按回车添加"
                />
              </n-form-item>
              
              <n-form-item label="评分">
                <n-rate 
                  v-model:value="inspirationSettings.rating" 
                  :count="5"
                  allow-half
                />
              </n-form-item>
              
              <n-form-item label="是否公开">
                <n-switch v-model:value="inspirationSettings.isPublic" />
              </n-form-item>
            </n-form>
          </div>
        </div>
        
        <!-- 临时便签页内容 -->
        <div v-for="tab in tempTabs" :key="tab.id" v-show="activeTab === tab.id" class="editor-pane">
          <div v-if="!isPreviewMode" class="editor-input-container">
            <n-input
              v-model:value="tab.content"
              type="textarea"
              placeholder="请输入内容，支持Markdown格式..."
              class="content-editor custom-scrollbar"
            />
            <!-- 内容加载遮罩动画 -->
            <div v-if="tab.isLoading" class="loading-overlay-container">
              <LoadingDots :visible="true" message="正在生成内容" />
            </div>
          </div>
          <div v-else class="preview-pane custom-scrollbar">
            <MarkdownRenderer :content="tab.content" />
            <!-- 内容加载遮罩动画 -->
            <div v-if="tab.isLoading" class="loading-overlay-container">
              <LoadingDots :visible="true" message="正在生成内容" />
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部标签页和按钮组 -->
    <div class="editor-tabs">
      <n-tabs 
        v-model:value="activeTab" 
        type="line" 
        animated 
        tab-position="bottom" 
        :tab-style="{ minWidth: '80px', maxWidth: '120px', height: '32px' }"
        :closable="false"
        @close="(name: string) => {
          // 处理主标签页的关闭事件（不允许关闭）
          if (name === 'content' || name === 'settings') return
          closeTempTab(name)
        }"
      >
        <template #suffix>
          <n-space :size="4">
            <!-- 主内容标签页按钮 -->
            <template v-if="activeTab === 'content'">
              <n-button @click="togglePreviewMode" :type="isPreviewMode ? 'primary' : 'default'" size="small">
                {{ isPreviewMode ? '编辑' : '预览' }}
              </n-button>
              <n-button @click="copyContent" size="small" :disabled="!inspirationContent.trim()">
                <template #icon>
                  <n-icon><CopyIcon /></n-icon>
                </template>
                复制
              </n-button>
              <n-button @click="clearContent" size="small" :disabled="!inspirationContent.trim()" type="warning">
                <template #icon>
                  <n-icon><DeleteIcon /></n-icon>
                </template>
                清空
              </n-button>
              <n-button @click="showEvaluateDialog" :disabled="!inspirationContent.trim()" size="small">
                评估
              </n-button>
              <n-button v-if="inspirationId" @click="resetInspiration" :disabled="loading" size="small" type="error">
                <template #icon>
                  <n-icon><RefreshIcon /></n-icon>
                </template>
                重置
              </n-button>
              <n-button type="primary" @click="saveInspiration" :loading="saving" size="small">
                保存
              </n-button>
            </template>
            
            <!-- 临时便签页按钮 -->
            <template v-for="tab in tempTabs" :key="tab.id">
              <template v-if="activeTab === tab.id">
                <n-button @click="togglePreviewMode" :type="isPreviewMode ? 'primary' : 'default'" size="small">
                  {{ isPreviewMode ? '编辑' : '预览' }}
                </n-button>
                <n-button @click="copyTempContent(tab.id)" size="small" :disabled="!tab.content.trim()">
                  <template #icon>
                    <n-icon><CopyIcon /></n-icon>
                  </template>
                  复制
                </n-button>
                <n-button @click="clearTempContent(tab.id)" size="small" :disabled="!tab.content.trim()" type="warning">
                  <template #icon>
                    <n-icon><DeleteIcon /></n-icon>
                  </template>
                  清空
                </n-button>
                <n-button @click="evaluateInNewTab(tab.id)" size="small">
                  评估
                </n-button>
              </template>
            </template>
          </n-space>
        </template>
        <n-tab-pane name="content" tab="内容编辑">
        </n-tab-pane>
        <n-tab-pane name="settings" tab="灵感设置">
        </n-tab-pane>
        
        <!-- 临时便签页 -->
        <n-tab-pane 
          v-for="tab in tempTabs" 
          :key="tab.id" 
          :name="tab.id" 
          :tab="tab.title"
          :closable="true"
        >
        </n-tab-pane>
      </n-tabs>
    </div>
    
    <!-- 生成内容对话框 -->
    <teleport to="body">
      <n-modal 
        v-model:show="generateContentDialogVisible" 
        preset="dialog" 
        title="生成灵感内容" 
        :mask-closable="false"
        style="width: 600px; max-width: 90vw;"
        class="generate-content-modal"
      >
        <template #header>
          <div>生成灵感内容</div>
        </template>
        
        <div class="generate-form">
          <n-form :model="generateContentForm" label-placement="left" label-width="100px">
            <n-form-item label="模型选择">
              <ModelSelector 
                :current-model="generateContentForm.modelId" 
                @select-model="handleContentModelSelect"
                model-tag="对话"
                direction="bottom"
              />
            </n-form-item>
            
            <n-form-item label="提示词模板">
              <PromptTemplateSelector 
                v-model="generateContentForm.systemPromptId"
                @select-template="handleContentTemplateSelect"
                category="灵感"
              />
            </n-form-item>
            
            <n-form-item label="用户提示">
              <n-input 
                v-model:value="generateContentForm.userPrompt" 
                type="textarea" 
                placeholder="请输入生成灵感内容的提示..."
                :autosize="{ minRows: 3, maxRows: 6 }"
              />
            </n-form-item>
          </n-form>
        </div>
        
        <template #action>
          <n-space justify="end">
            <n-button @click="generateContentDialogVisible = false">取消</n-button>
            <n-button type="primary" @click="generateContent" :loading="generatingContent">
              生成内容
            </n-button>
          </n-space>
        </template>
      </n-modal>
    </teleport>
    
    <!-- 评估对话框 -->
    <teleport to="body">
      <n-modal 
        v-model:show="evaluateDialogVisible" 
        preset="dialog" 
        title="评估灵感" 
        :mask-closable="false"
        style="width: 600px; max-width: 90vw;"
        class="evaluate-modal"
      >
        <template #header>
          <div>评估灵感</div>
        </template>
        
        <div class="evaluate-form">
          <n-form :model="evaluateForm" label-placement="left" label-width="100px">
            <n-form-item label="模型选择">
              <ModelSelector 
                :current-model="evaluateForm.modelId" 
                @select-model="handleEvaluateModelSelect"
                model-tag="对话"
                direction="bottom"
              />
            </n-form-item>
            
            <n-form-item label="提示词模板">
              <PromptTemplateSelector 
                v-model="evaluateForm.systemPromptId"
                @select-template="handleEvaluateTemplateSelect"
                category="灵感"
              />
            </n-form-item>
            
            <n-form-item label="生成方式">
              <n-radio-group v-model:value="evaluateForm.appendMode" name="appendMode" vertical>
                <n-radio value="append">追加生成</n-radio>
                <div style="margin-left: 24px; margin-top: 4px; font-size: 12px; color: #999;">
                  在现有内容后继续生成
                </div>
                <n-radio value="overwrite">覆盖生成</n-radio>
                <div style="margin-left: 24px; margin-top: 4px; font-size: 12px; color: #999;">
                  清空当前内容重新生成
                </div>
                <n-radio value="newTab">在新标签页生成</n-radio>
                <div style="margin-left: 24px; margin-top: 4px; font-size: 12px; color: #999;">
                  在新的临时标签页中生成内容，不影响当前编辑内容
                </div>
              </n-radio-group>
            </n-form-item>
          </n-form>
        </div>
        
        <template #action>
          <n-space justify="end">
            <n-button @click="evaluateDialogVisible = false">取消</n-button>
            <n-button type="primary" @click="evaluateInspiration" :loading="evaluating">
              开始评估
            </n-button>
          </n-space>
        </template>
      </n-modal>
    </teleport>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage, useDialog } from 'naive-ui'
import { Copy as CopyIcon, Trash as DeleteIcon, Refresh as RefreshIcon } from '@vicons/tabler'
import { inspirationService } from '../../book/services/inspiration-service'
import { useUserStore } from '../../auth/stores/user'
import MarkdownRenderer from '../../shared/components/MarkdownRenderer.vue'
import LoadingDots from '../../shared/components/LoadingDots.vue'
import ModelSelector from '../../chat/components/ModelSelector.vue'
import PromptTemplateSelector from '../../prompt/components/PromptTemplateSelector.vue'

const route = useRoute()
const router = useRouter()
const message = useMessage()
const dialog = useDialog()
const userStore = useUserStore()

// 灵感ID
const inspirationId = ref<string | null>(null)

// 加载状态
const loading = ref(false)
const saving = ref(false)
const contentLoading = ref(false)
const generatingContent = ref(false)

// 是否为新建灵感
const isNew = computed(() => !inspirationId.value)

// 是否为空状态
const isEmpty = computed(() => !inspirationContent.value && !inspirationSettings.value.title)

// 当前活动标签页
const activeTab = ref('content')

// 临时便签页管理
const tempTabs = ref<Array<{
  id: string
  title: string
  content: string
  isActive: boolean
  isLoading: boolean // 添加加载状态字段
}>>([])

// 预览模式
const isPreviewMode = ref(false)

// 灵感内容
const inspirationContent = ref('')

// 灵感设置
const inspirationSettings = ref({
  title: '',
  tags: [] as string[],
  rating: 3,
  isPublic: false
})

// 生成内容对话框
const generateContentDialogVisible = ref(false)
const generateContentForm = ref({
  modelId: '',
  systemPromptId: 13, // 设置默认值，与大纲编辑器保持一致
  userPrompt: ''
})

// 评估对话框
const evaluateDialogVisible = ref(false)
const evaluateForm = ref({
  modelId: '',
  systemPromptId: 13, // 设置默认值，与大纲编辑器保持一致
  appendMode: 'append' // 生成方式：'append'(追加生成)、'overwrite'(覆盖生成)、'newTab'(在新标签页生成)
})
const evaluating = ref(false)

// 创建新的临时便签页
const createTempTab = (title: string = '新便签') => {
  const tabId = `temp_${Date.now()}`
  const newTab = {
    id: tabId,
    title: title,
    content: '',
    isActive: true,
    isLoading: false // 初始化加载状态为false
  }
  
  // 将所有现有标签页设为非活动状态
  tempTabs.value.forEach(tab => {
    tab.isActive = false
  })
  
  // 添加新标签页
  tempTabs.value.push(newTab)
  
  return tabId
}

// 关闭临时便签页
const closeTempTab = (tabId: string) => {
  const tabIndex = tempTabs.value.findIndex(tab => tab.id === tabId)
  if (tabIndex === -1) return
  
  const wasActive = activeTab.value === tabId
  
  // 移除标签页
  tempTabs.value.splice(tabIndex, 1)
  
  // 如果关闭的是活动标签页，则切换到其他标签页
  if (wasActive) {
    if (tempTabs.value.length > 0) {
      // 切换到最后一个标签页
      activeTab.value = tempTabs.value[tempTabs.value.length - 1].id
    } else {
      // 如果没有其他临时标签页，切换到主内容标签页
      activeTab.value = 'content'
    }
  }
}

// 切换预览模式
const togglePreviewMode = () => {
  isPreviewMode.value = !isPreviewMode.value
}



// 显示评估对话框
const showEvaluateDialog = () => {
  evaluateDialogVisible.value = true
}

// 复制临时便签页内容
const copyTempContent = async (tabId: string) => {
  const tab = tempTabs.value.find(t => t.id === tabId)
  if (!tab || !tab.content.trim()) {
    message.warning('没有可复制的内容')
    return
  }
  
  try {
    await navigator.clipboard.writeText(tab.content)
    message.success('内容已复制到剪贴板')
  } catch (err) {
    message.error('复制失败，请手动复制')
  }
}

// 清空临时便签页内容
const clearTempContent = (tabId: string) => {
  const tab = tempTabs.value.find(t => t.id === tabId)
  if (!tab || !tab.content.trim()) {
    message.warning('没有可清空的内容')
    return
  }
  
  dialog.warning({
    title: '确认清空',
    content: '确定要清空当前内容吗？此操作不可恢复。',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      tab.content = ''
      message.success('内容已清空')
    }
  })
}

// 在临时便签页中评估
const evaluateInNewTab = (tabId: string) => {
  const tab = tempTabs.value.find(t => t.id === tabId)
  if (!tab) return
  
  // 设置当前活动标签页
  activeTab.value = tabId
  
  // 显示评估对话框
  evaluateDialogVisible.value = true
}

// 复制内容
const copyContent = async () => {
  if (!inspirationContent.value.trim()) {
    message.warning('没有可复制的内容')
    return
  }
  
  try {
    await navigator.clipboard.writeText(inspirationContent.value)
    message.success('内容已复制到剪贴板')
  } catch (err) {
    message.error('复制失败，请手动复制')
  }
}

// 清空内容
const clearContent = () => {
  if (!inspirationContent.value.trim()) {
    message.warning('没有可清空的内容')
    return
  }
  
  dialog.warning({
    title: '确认清空',
    content: '确定要清空当前灵感内容吗？此操作不可恢复。',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      inspirationContent.value = ''
      message.success('内容已清空')
    }
  })
}

// 处理模型选择
const handleContentModelSelect = (modelId: string) => {
  generateContentForm.value.modelId = modelId
}

// 处理模板选择
const handleContentTemplateSelect = (template: any) => {
  // 根据传入的参数类型处理，可能是对象或ID
  if (typeof template === 'object' && template.id) {
    generateContentForm.value.systemPromptId = template.id
  } else if (typeof template === 'number') {
    generateContentForm.value.systemPromptId = template
  }
}

// 处理评估模型选择
const handleEvaluateModelSelect = (modelId: string) => {
  evaluateForm.value.modelId = modelId
}

// 处理评估模板选择
const handleEvaluateTemplateSelect = (template: any) => {
  // 根据传入的参数类型处理，可能是对象或ID
  if (typeof template === 'object' && template.id) {
    evaluateForm.value.systemPromptId = template.id
  } else if (typeof template === 'number') {
    evaluateForm.value.systemPromptId = template
  }
}

// 生成内容
const generateContent = async () => {
  if (!generateContentForm.value.modelId) {
    message.error('请选择模型')
    return
  }

  if (!generateContentForm.value.systemPromptId) {
    message.error('请选择提示词模板')
    return
  }

  if (!generateContentForm.value.userPrompt.trim()) {
    message.warning('请输入生成提示')
    return
  }

  generatingContent.value = true
  contentLoading.value = true

  try {
    // 这里应该调用AI生成接口，暂时模拟
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 模拟生成的内容
    const generatedContent = `# ${generateContentForm.value.userPrompt}\n\n这是根据您的提示生成的灵感内容。您可以在此基础上进行修改和完善。`
    
    inspirationContent.value = generatedContent
    generateContentDialogVisible.value = false
    message.success('内容生成成功')
  } catch (error) {
    console.error('生成内容失败:', error)
    message.error('生成内容失败')
  } finally {
    generatingContent.value = false
    contentLoading.value = false
  }
}

// 评估灵感
const evaluateInspiration = async () => {
  if (!evaluateForm.value.modelId) {
    message.error('请选择模型')
    return
  }

  if (!evaluateForm.value.systemPromptId) {
    message.error('请选择提示词模板')
    return
  }

  // 检查是否在新标签页生成
  if (evaluateForm.value.appendMode === 'newTab') {
    // 创建新标签页
    const tabId = createTempTab('评估结果')
    activeTab.value = tabId
    
    // 关闭对话框
    evaluateDialogVisible.value = false
    
    // 获取新创建的标签页
    const tab = tempTabs.value.find(t => t.id === tabId)
    if (!tab) return
    
    // 开始生成内容
    evaluating.value = true
    tab.isLoading = true // 设置标签页加载状态

    try {
      // 调用流式接口
      const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8080'}/common/stream/generate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          modelId: evaluateForm.value.modelId,
          systemPromptId: evaluateForm.value.systemPromptId,
          userPrompt: inspirationContent.value,
          business: '评估灵感'
        })
      })

      if (!response.ok) {
        throw new Error('评估失败')
      }

      // 清空当前内容
      tab.content = ''

      // 在开始接收流式数据前停止加载动画，让用户看到打字机效果
      tab.isLoading = false

      const reader = response.body?.getReader()
      if (!reader) {
        throw new Error('无法获取响应流')
      }
      const decoder = new TextDecoder()

      // 处理流式数据
      while (true) {
        const { done, value } = await reader.read()

        if (done) {
          break
        }

        // 后端返回的是纯文本流，不是JSON格式
        const chunk = decoder.decode(value, { stream: true })

        // 直接将文本块添加到内容中
        if (chunk) {
          tab.content += chunk
        }
      }

      message.success('评估完成')
    } catch (error) {
      console.error('评估失败:', error)
      tab.isLoading = false // 确保在错误情况下也停止加载动画
      message.error('评估失败，请稍后重试')
    } finally {
      evaluating.value = false
    }
  } else {
    // 原有逻辑：在当前标签页生成
    if (!inspirationContent.value.trim()) {
      message.error('请先输入灵感内容')
      return
    }

    evaluating.value = true
    evaluateDialogVisible.value = false
    contentLoading.value = true

    try {
      // 保存原始内容，以防接口调用失败
      const originalContent = inspirationContent.value

      // 调用流式接口
      const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8080'}/common/stream/generate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          modelId: evaluateForm.value.modelId,
          systemPromptId: evaluateForm.value.systemPromptId,
          userPrompt: inspirationContent.value,
          business: '评估灵感'
        })
      })

      if (!response.ok) {
        // 恢复原始内容
        inspirationContent.value = originalContent
        throw new Error('评估失败')
      }

      // 根据生成方式决定是否清空当前内容
      if (evaluateForm.value.appendMode === 'overwrite') {
        inspirationContent.value = ''
      }

      // 在开始接收流式数据前停止加载动画，让用户看到打字机效果
      contentLoading.value = false

      const reader = response.body?.getReader()
      if (!reader) {
        throw new Error('无法获取响应流')
      }
      const decoder = new TextDecoder()

      // 处理流式数据
      while (true) {
        const { done, value } = await reader.read()

        if (done) {
          break
        }

        // 后端返回的是纯文本流，不是JSON格式
        const chunk = decoder.decode(value, { stream: true })

        // 直接将文本块添加到内容中
        if (chunk) {
          inspirationContent.value += chunk
        }
      }

      message.success('评估完成')
    } catch (error) {
      console.error('评估失败:', error)
      contentLoading.value = false
      message.error('评估失败，请稍后重试')
    } finally {
      evaluating.value = false
    }
  }
}

// 保存灵感
const saveInspiration = async () => {
  if (!inspirationSettings.value.title.trim()) {
    message.warning('请输入灵感标题')
    return
  }

  saving.value = true

  try {
    const data = {
      title: inspirationSettings.value.title,
      content: inspirationContent.value,
      tags: inspirationSettings.value.tags.join(','),
      rating: inspirationSettings.value.rating,
      isPublic: inspirationSettings.value.isPublic ? 1 : 0  // 将布尔值转换为整数
    }

    let response
    if (inspirationId.value) {
      // 更新现有灵感，需要在请求体中包含ID
      const updateData = {
        ...data,
        id: Number(inspirationId.value)
      }
      response = await inspirationService.updateInspiration(Number(inspirationId.value), updateData)
    } else {
      // 创建新灵感
      response = await inspirationService.createInspiration({
        ...data,
        userId: userStore.currentUserId
      })
    }

    if (response.code === 0) {
      message.success(inspirationId.value ? '更新成功' : '创建成功')
      
      // 如果是新建灵感，更新ID
      if (!inspirationId.value && response.data?.id) {
        inspirationId.value = String(response.data.id)
        // 更新路由
        router.replace({
          path: `/books/workspace/${route.params.id}/inspiration/${response.data.id}`
        })
      }
    } else {
      message.error(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存灵感失败:', error)
    message.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 加载灵感详情
const loadInspiration = async (id: string) => {
  if (!id) return

  loading.value = true
  try {
    const response = await inspirationService.getInspirationById(Number(id))
    if (response.code === 0 && response.data) {
      const inspiration = response.data
      
      // 更新灵感内容
      inspirationContent.value = inspiration.content || ''
      
      // 更新灵感设置
      inspirationSettings.value = {
        title: inspiration.title || '',
        tags: inspiration.tags ? inspiration.tags.split(',').filter(tag => tag.trim()) : [],
        rating: inspiration.rating || 3,
        isPublic: inspiration.isPublic === 1  // 将整数转换为布尔值
      }
    } else {
      message.error(response.msg || '获取灵感详情失败')
    }
  } catch (error) {
    console.error('加载灵感详情失败:', error)
    message.error('加载灵感详情失败')
  } finally {
    loading.value = false
  }
}

// 重置灵感
const resetInspiration = () => {
  if (!inspirationId.value) {
    message.warning('无法重置新建灵感')
    return
  }

  dialog.warning({
    title: '确认重置',
    content: '确定要重置当前灵感吗？此操作将撤销所有未保存的修改，并从服务器重新加载原始数据。',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      loadInspiration(inspirationId.value!)
      message.success('灵感已重置')
    }
  })
}

// 处理新建灵感
const handleAddInspiration = () => {
  inspirationId.value = null
  inspirationContent.value = ''
  inspirationSettings.value = {
    title: '',
    tags: [],
    rating: 3,
    isPublic: false
  }
}

// 监听路由参数变化
watch(
  () => route.params.inspirationId,
  (newId) => {
    if (newId && typeof newId === 'string') {
      inspirationId.value = newId
      loadInspiration(newId)
    } else {
      // 没有ID，视为新建灵感
      handleAddInspiration()
    }
  },
  { immediate: true }
)

// 页面加载时处理
onMounted(() => {
  // 从路由参数获取灵感ID
  const id = route.params.inspirationId
  if (id && typeof id === 'string') {
    inspirationId.value = id
    loadInspiration(id)
  } else {
    // 没有ID，视为新建灵感
    handleAddInspiration()
  }
})
</script>

<style scoped>
.inspiration-editor {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #ffffff;
  overflow: hidden;
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  gap: 16px;
}

.loading-text {
  color: #666;
  font-size: 14px;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.editor-container {
  display: flex;
  flex-direction: column;
  height: calc(100% - 34px);
  flex: 1;
  overflow: hidden;
}

.editor-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.editor-pane {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.editor-input-container {
  height: 100%;
  position: relative;
}

.content-editor {
  height: 100%;
  font-size: 16px;
  line-height: 1.6;
}

.preview-pane {
  height: 100%;
  padding: 16px;
  overflow-y: auto;
  background-color: #fafafa;
}

.settings-form {
  padding: 16px;
  overflow-y: auto;
  flex: 1;
}

.loading-overlay-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.editor-tabs {
  border-top: 1px solid #eee;
  background-color: #ffffff;
  flex-shrink: 0;
  height: 34px;
  position: relative;
  z-index: 10;
}

.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: #ddd transparent;
}

.custom-scrollbar::-webkit-scrollbar {
  width: 8px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 4px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background-color: #ccc;
}

/* 生成内容对话框样式 */
.generate-content-modal {
  max-height: 80vh;
}

.generate-form {
  max-height: 60vh;
  overflow-y: auto;
}

/* 评估对话框样式 */
.evaluate-modal {
  max-height: 80vh;
}

.evaluate-form {
  max-height: 60vh;
  overflow-y: auto;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .settings-form {
    padding: 12px;
  }
  
  .preview-pane {
    padding: 12px;
  }
}
</style>